package ecoiot.com.testproject.webview;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import ecoiot.com.testproject.R;

/**
 * Created by developer on 17-11-14.
 */

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class HeaderWebViewActivity extends AppCompatActivity {

    private WebView webView;
    private Button btn;
    private TextView tv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_head_web);
        webView = (WebView) findViewById(R.id.head_web_wb);

        Map<String, String> extraHeaders = new HashMap<>();
        extraHeaders.put("Accept", "application/json, text/javascript, */*; q=0.01");
        extraHeaders.put("Accept-Encoding", "gzip, deflate");
        extraHeaders.put("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ms;q=0.2");
        extraHeaders.put("Referer", "https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm");
        extraHeaders.put("Content-Type", "application/x-www-form-urlencoded");
        extraHeaders.put("x-requested-with", "XMLHttpRequest");

        String url = "https://buyertrade.taobao.com/trade/itemlist/asyncBought.htm?action=itemlist/BoughtQueryAction&event_submit_do_query=1&_input_charset=utf8";

        webView.loadUrl(url,extraHeaders);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString(),request.getRequestHeaders());
                return true;
            }
        });

        btn = (Button) findViewById(R.id.head_web_btn);
        tv = (TextView) findViewById(R.id.head_web_tv);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestConnection();
            }
        });

    }

    private void requestConnection() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    final byte[] bytes = new byte[1024];

                    URL url = new URL("https://buyertrade.taobao.com/trade/itemlist/asyncBought.htm?action=itemlist/BoughtQueryAction&event_submit_do_query=1&_input_charset=utf8");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setInstanceFollowRedirects(false);
                    connection.setUseCaches(false);
                    connection.addRequestProperty("x-requested-with", "XMLHttpRequest");
                    connection.addRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                    connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
                    connection.addRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ms;q=0.2");
                    connection.addRequestProperty("Referer", "https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm");
                    connection.addRequestProperty("Cookie", CookieManager.getInstance().getCookie("https://buyertrade.taobao.com/trade/itemlist/asyncBought.htm?action=itemlist/BoughtQueryAction&event_submit_do_query=1&_input_charset=utf8"));
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    connection.getOutputStream().write(bytes);
                    connection.connect();

                    String contentEncoding = connection.getContentEncoding();
                    String string = "";
                    if (!TextUtils.isEmpty(contentEncoding) && contentEncoding.contains("gzip")) {
                        string = IoUtils.readString((InputStream)new GZIPInputStream(connection.getInputStream()));
                    }else {
                        string = IoUtils.readString(connection.getInputStream());
                    }

                     Log.e("response",string);

//                    if(200 == connection.getResponseCode()) {
//                        InputStream is = connection.getInputStream();
//                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                        byte[] buffer = new byte[1024];
//                        int len = 0;
//                        while(-1 != (len = is.read(buffer))){
//                            baos.write(buffer,0,len);
//                            baos.flush();
//                        }
//
//                        final String responseStr = baos.toString("utf-8");
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                tv.setText(responseStr);
//                            }
//                        });
//                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
